package http

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"wecom_rebot/utils"
)

type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

type ListResponse[T any] struct {
	Count int64 `json:"count"`
	List  T     `json:"list"`
}

const (
	Success = 0
	Error   = -1
)

// Result 返回数据
func Result(code int, data interface{}, msg string, c *gin.Context) {
	c.JSON(http.StatusOK, Response{
		Code: code,
		Data: data,
		Msg:  msg,
	})
	return
}

// IsOk 成功响应
func IsOk(data interface{}, msg string, c *gin.Context) {
	Result(Success, data, msg, c)
}

// IsOkWithData 含 data
func IsOkWithData(data interface{}, c *gin.Context) {
	Result(Success, data, "成功", c)
}

// IsOkWithList 返回列表数据
func IsOkWithList(list any, count int64, c *gin.Context) {
	IsOkWithData(ListResponse[any]{
		Count: count,
		List:  list,
	}, c)
}

// IsOkWithMessage 含 msg
func IsOkWithMessage(msg string, c *gin.Context) {
	Result(Success, []interface{}{}, msg, c)
}

// Fail 错误返回
func Fail(data interface{}, msg string, c *gin.Context) {
	Result(Error, data, msg, c)
}

// FailWithMessage 含 msg
func FailWithMessage(msg string, c *gin.Context) {
	Result(Error, []interface{}{}, msg, c)
}

// FailWithError 自定义结构体抛出指定字段异常
func FailWithError(err error, obj any, c *gin.Context) {
	msg := utils.GetValidateMsg(err, obj)
	FailWithMessage(msg, c)
}

// FailWithCode 自定义code返回
func FailWithCode(code ErrorCode, c *gin.Context) {
	msg, ok := ErrorMap[code]
	if ok {
		Result(int(code), map[string]interface{}{}, msg, c)
		return
	}
	Result(Error, map[string]interface{}{}, "未知错误", c)
}
